package comment_api

import (
	"github.com/gin-gonic/gin"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/es_ser"
	"giv-vue-blog/service/redis_ser"
	"giv-vue-blog/utils/jwts"
	"gorm.io/gorm"
)

type CommentRequest struct {
	ArticleID       string `json:"article_id" binding:"required" msg:"请选择文章"`
	Content         string `json:"content" binding:"required" msg:"请输入评论内容"`
	ParentCommentID *uint  `json:"parent_comment_id"` //父评论
}

// CommentCreateView 创建评论
// @Summary 创建评论
// @Tags 评论管理
// @Accept json
// @Produce json
// @Param request body CommentRequest true "评论请求参数"
// @Success 200 {string} json "{"code": 0, "message": "文章评论成功"}"
// @Failure 400 {string} json "{"code": 1, "message": "参数错误"}"
// @Failure 401 {string} json "{"code": 2, "message": "未授权访问"}"
// @Failure 404 {string} json "{"code": 3, "message": "文章不存在"}"
// @Failure 500 {string} json "{"code": 4, "message": "服务器内部错误"}"
// @Router /api/comments [post]
func (CommentApi) CommentCreateView(c *gin.Context) {
	var cr CommentRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailedWithCode(res.ArgumentError, c)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.CustomClaims)
	//判断文章是否存在
	_, err = es_ser.CommonDetail(cr.ArticleID)
	if err != nil {
		res.FailedWithMsg("文章不存在", c)
		return
	}
	//判断是否是子评论
	if cr.ParentCommentID != nil {
		//子评论
		//父评论id
		var parentComment models.CommentModel
		//找父评论id
		err = global.DB.Take(&parentComment, cr.ParentCommentID).Error
		if err != nil {
			res.FailedWithMsg("父评论id不存在", c)
			return
		}
		//判断父评论的文章是否与当前文章一致
		if parentComment.ArticleID != cr.ArticleID {
			res.FailedWithMsg("评论文章不一致", c)
			return
		}
		//给父评论数加1
		global.DB.Model(&parentComment).Update("comment_count", gorm.Expr("comment_count+1"))
	}
	//添加评论
	global.DB.Create(&models.CommentModel{
		ParentCommentID: cr.ParentCommentID,
		Content:         cr.Content,
		ArticleID:       cr.ArticleID,
		UserID:          claims.UserID,
	})
	//拿到文章数 新的文章评论数存缓存里
	//newCommentCount := article.CommentCount + 1
	//给文章评论数加1
	_ = redis_ser.NewComment().Set(cr.ArticleID)
	res.OkWithMsg("文章评论成功", c)
	return
}
